#include "applycertificatefunctionality.h"
#include "Modules/TcpNetwork.h"
#include "openssl/types.h"
#include "utils/certificatemanager.h"
#include <iostream>
applyCertificateFunctionality::applyCertificateFunctionality(
    std::shared_ptr<NetworkInterface> network, std::shared_ptr<ModuleInterface> module)
    : FunctionalityInterface()
    , m_network(network)
    , m_module(module)
{
    bool ret = m_module->initialize();
    if (!ret) {
        std::cerr << "Failed to initialize module!" << std::endl;
        return;
    }

    m_network->connect("172.21.93.12", 10001);

    //std::dynamic_pointer_cast是转换为share_ptr类型的派生类的指针
    auto tcpNetwork = std::dynamic_pointer_cast<TcpNetwork>(m_network);

    QObject::connect(tcpNetwork.get(),
                     &TcpNetwork::dataArrival,
                     this,
                     &applyCertificateFunctionality::onDataArrival);
}

bool applyCertificateFunctionality::executeFunction()
{
    QByteArray data = m_module->execute();
    if (data.isEmpty()) {
        std::cerr << "Failed to execute module!" << std::endl;
        return false;
    }

    m_network->sendData(data);
    return true;
}

void applyCertificateFunctionality::stopNetwork()
{
    m_network->disconnect();
}

void applyCertificateFunctionality::onDataArrival(qint64 readBytes)
{
    //这里应该是将数据处理交给证书处理模块的
    QByteArray data = m_network->readData(readBytes);
    if (m_module->handleReceiveData(data)) {
        qDebug() << "证书获取成功";
    }
}
